package elasticsearch

import (
	"context"
	"fmt"
	"github.com/olivere/elastic"
	"github.com/pkg/errors"
	"my-new-gin/configs"
	"sync"
	"time"
)
var (
	client *elastic.Client
	once sync.Once
)


func GetESClilent(conf configs.ElasticsearchConf) (*elastic.Client, error) {
	var err error
	once.Do(func() {
		host := fmt.Sprintf("http://%s:%s",conf.Ip,conf.Port)
		//创建一个空值的上下文，用于整合传递参数与适配运行状态
		ctx := context.Background()
		//通过NewClient创建的client会自动start，无须显式Start(),当然写了也无妨
		client, err = elastic.NewClient(
			/* 设置elastic服务实例ip
					* DefaultURL = "http://127.0.0.1:9200"
				*/
			elastic.SetURL(host),

			/* 监视时使用的协议，默认是http
				* DefaultScheme = "http"
			 */
			elastic.SetScheme("http"),

			//设置健康检查
			elastic.SetHealthcheck(true),
			elastic.SetHealthcheckTimeoutStartup(5*time.Second),
			elastic.SetHealthcheckTimeout(1*time.Second),
			elastic.SetHealthcheckInterval(60*time.Second),

			//设置嗅探监测
			elastic.SetSniff(false),
			elastic.SetSnifferInterval(15*time.Minute),
			elastic.SetSnifferTimeoutStartup(5*time.Second),
			elastic.SetSnifferTimeout(2*time.Second),
			//设置request方式
			elastic.SetSendGetBodyAs("GET"),
		)
		//1.client通过newclient创建默认开启，所以true
		//http://10.0.203.92:9200 [dead=false,failures=0,deadSince=<nil>],true
		fmt.Println("96 Line--->",client.String(), client.IsRunning())

		//2.关开client
		//client.Stop()
		//false
		//fmt.Println("101 Line--->",client.IsRunning())
		//client.Start()
		//true
		//fmt.Println("104 Line--->",client.IsRunning())

		//3.Ping一下es服务
		var info *elastic.PingResult
		var code int
		info, code, err = client.Ping(host).Do(ctx)
		//Elasticsearch returned with code 200 and version 6.2.2
		fmt.Printf("112 Line ---> Elasticsearch returned with code %d and version %s\n", code, info.Version.Number)

		//4.获取es版本信息
		//可以直接curl localhost:9200 查看,也可以浏览器输入localhost:9200查看
		var version string
		version, err = client.ElasticsearchVersion(host)
		//Elasticsearch version 6.2.2
		fmt.Printf("121 Line---> Elasticsearch version %s\n", version)
	})
	return client, err
}

func CreateIndexAndMapping(idx string,mp string) error {
	ctx := context.Background()
	exists, err := client.IndexExists(idx).Do(ctx)
	if err != nil {
		return err
	}
	if !exists {
		createIndex, err := client.CreateIndex(idx).BodyString(mp).Do(ctx)
		if err != nil {
			return err
		}
		if !createIndex.Acknowledged {
			return errors.New("request not found")
		}
	}else{
		fmt.Printf("index %s exists \n",idx)
	}
	return nil
}